<style>
    .lay-dialog-title{
        padding: 0 20px;
        position: relative;
        z-index: 99;
        border-bottom: 1px solid #e5e5e5;
        line-height: 39px;
        height: 39px;
        overflow: hidden;
        color: #666;
    }
    .lay-dialog-title label{color: #999}
    .samplingAmount{
        height: 28px !important;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">柜子类型：</label>
                                    <div class="layui-input-inline">
                                        <select name="typeOfEnterprise">
                                            <option value="">柜子类型</option>
                                            <option value="settled">入驻企业</option>
                                            <option value="selfEmployed">自营企业</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">渠道品牌：</label>
                                    <div class="layui-input-inline">
                                        <select name="typeOfEnterprise">
                                            <option value="">渠道品牌</option>
                                            <option value="settled">入驻企业</option>
                                            <option value="selfEmployed">自营企业</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">需求状态：</label>
                                    <div class="layui-input-inline">
                                        <select name="typeOfEnterprise">
                                            <option value="">需求状态</option>
                                            <option value="settled">入驻企业</option>
                                            <option value="selfEmployed">自营企业</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">所需车间：</label>
                                    <div class="layui-input-inline">
                                        <select name="typeOfEnterprise">
                                            <option value="">所需车间</option>
                                            <option value="settled">入驻企业</option>
                                            <option value="selfEmployed">自营企业</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">柜子编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" id="pName" class="layui-input" type="text" placeholder="柜子编号"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
<!--                            <button id="distributionDemandPlanBtnAdd" class="layui-btn icon-btn color-reseda">添加配货需求</button>-->
                        </div>
                        <div class="lay-btn-rt">
                            <button id="distributionDemandPlanBtnProduce" class="layui-btn icon-btn color-gray">生成配货单</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="distributionDemandPlanTable" lay-filter="distributionDemandPlanTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="distributionDemandPlanTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="dtl">详情</a>
    {{# if(d.status != 'done' && d.dataSourceType =='1'){  }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="create">生成配货单</a>
    {{# } }}

</script>

<!-- 表单详情弹窗 -->
<script type="text/html" id="distributionDemandPlanDetail">
    <div class="lay-dialog-title">
        <span>刀柜售刀柜库存告警信息详情</span>
    </div>
    <form lay-filter="distributionDemandPlanDetail" class="layui-form model-form">
        <div class="layui-card-body" style="padding: 0 20px">
            <!-- 表格 -->
            <table class="layui-table" id="orderDetailTable" lay-filter="orderDetailTable"></table>
        </div>
        <div class="layui-card-body" style="padding: 30px 20px 50px">
            <!-- 表格 -->
            <table class="layui-table" id="childOrdersTable" lay-filter="childOrdersTable"></table>
        </div>
    </form>
</script>

<!--生成配货单弹窗-->
<script type="text/html" id="distributionOrderTableTemp">
    <form lay-filter="distributionOrderForm" class="layui-form model-form">
        <div class="layui-form-item" style="margin-left: 20px">
            <div class="layui-inline">
                <a id="batchProduce" class="layui-btn icon-btn">确认生成</a>
            </div>
        </div>
        <div class="layui-card-body" style="padding: 0 20px 50px">
            <!-- 表格 -->
            <table class="layui-table" id="distributionOrderTable" lay-filter="distributionOrderTable"></table>
        </div>
    </form>
</script>

<!-- 生成配货单表格操作列 -->
<script type="text/html" id="distributionOrderTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="dtl">详情</a>
    {{# if(d.status == 'replay'){  }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="affirm">确认生成</a>
    {{# } }}

</script>
<script type="text/html" id="distributionOrderTableBar2">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="dtl">详情</a>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var distributionOrderTable;
        var currentPageData=[];
        var checkedMap=new Map();
        var checkedData=[];

        // 渲染表格
        var insTb = table.render({
            elem: '#distributionDemandPlanTable',
            url: config.base + 'enterprisecab/order/admin/distributionDemandPlan/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'}
                ,{field: 'disbCode',title: '需求编号'}
                ,{field: 'workshopName', sort: true, title: '所属车间'}
                ,{field: 'cabCode', title: '柜子编号'}
                ,{field: 'workshopId', title: '物料编号'}
                ,{field: 'workshopId', title: '物料名称'}
                ,{field: 'specCode', title: '规格'}
                ,{field: 'unitId', title: '单位'}
                ,{field: 'curentStock', sort: true, title: '当前库存'}
                ,{field: 'alarmStock', sort: true, title: '告警数'}
                ,{field: 'planReplenishment', sort: true, title: '计划补货'}
                ,{field: 'statusDesc',  title: '状态'}
                ,{field: 'createTime', title: '计划生成时间'}
                ,{align: 'center', toolbar: '#distributionDemandPlanTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {
                currentPageData=res.data;
                var isCheckAll=true;
                var isAllGenOrder=true;
                for(var k=0;k<res.data.length;k++){
                    res.data[k].LAY_CHECKED = true;
                    var index= res.data[k]['LAY_TABLE_INDEX'];
                    var checkbox = $('#'+'distributionDemandPlanTable'+'').next().find('tr[data-index=' + index + '] input[type="checkbox"]');
                    if(checkedMap.get(res.data[k].id)){
                        checkbox.prop('checked', true).next().addClass('layui-form-checked');
                    }else{
                        isCheckAll=false;
                    }
                    if(res.data[k].dataSourceType !='1' || res.data[k].status == 'done'){
                        $(checkbox[0]).parent().remove();
                    }else{
                        isAllGenOrder=false;
                    }
                }
                if(isCheckAll){
                    $('[lay-filter="layTableAllChoose"]').prop('checked', true).next().addClass('layui-form-checked');
                }
                if(isAllGenOrder){
                    $($('[lay-filter="layTableAllChoose"]')[0]).parent().hide();
                }else{
                    $($('[lay-filter="layTableAllChoose"]')[0]).parent().show();
                }
            }
        });
        //渲染下拉框
        form.render('select');

        // 工具条点击事件
        table.on('tool(distributionDemandPlanTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'dtl') { //详情
                showDetailModel(data);
            } else if (obj.event === 'create') { // 生成配货单
                if (data.status == 'replay'){
                    let tableData = [];
                    tableData.push(data);
                    tableData.forEach((item, index) => {
                        tableData[index].quantityConfirm = tableData[index].planReplenishment;
                    })
                    createOrderBlank(tableData, '1');
                }else {
                    layer.msg('选择的配货单已生成', {icon: 5});
                    return false;
                }

            }
        });

        //table选择
        table.on('checkbox(distributionDemandPlanTable)', function(obj){
            var data = obj.data;
            if(obj.type=='all'){
                if(obj.checked){
                    var checkStatus = table.checkStatus('distributionDemandPlanTable')
                    var checkedAllData = checkStatus.data;
                    checkedAllData.forEach(item=> {
                        if(item.dataSourceType =='1' && item.status != 'done'){
                            if (checkedMap.get(item.id) == undefined) {
                                checkedData.push(item);
                            }
                            checkedMap.set(item.id,item.id);
                        }

                    })


                }else{
                    currentPageData.forEach(item=>{
                        if(checkedMap.get(item.id)!=undefined){
                            checkedData=checkedData.filter(item2=>{
                                if(item.id==item2.id){
                                    return false;
                                }
                                return  true;
                            })
                        }
                        checkedMap.delete(item.id);

                    })
                }
            }else{
                if(obj.checked){
                    if (checkedMap.get(data.id) == undefined) {
                        checkedData.push(data);
                    }
                    checkedMap.set(data.id,data.id);
                }else{
                    if(checkedMap.get(data.id)!=undefined){
                        checkedData=checkedData.filter(item=>{
                            if(item.id==data.id){
                                return false;
                            }
                            return  true;
                        })
                    }
                    checkedMap.delete(data.id);
                }
                var isAllChecked=true;
                currentPageData.forEach(item=>{
                    if(item.dataSourceType =='1' && item.status != 'done'){
                        if(checkedMap.get(item.id)==undefined){
                            isAllChecked=false;
                        }
                    }

                });
                if(isAllChecked){
                    $('[lay-filter="layTableAllChoose"]').prop('checked', true).next().addClass('layui-form-checked');
                }else{
                    $('[lay-filter="layTableAllChoose"]').prop('checked', false).next().removeClass('layui-form-checked');
                }
            }

        });


        //监听排序
        table.on('sort(distributionDemandPlanTable)', function(obj){
            table.reload('distributionDemandPlanTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field,page: {curr: 1}},'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            var field = data.field;
            for(let key in field){
                field[key] = ''
            }
            insTb.reload({where: field,page: {curr: 1}},'data');
        });

        // 批量生成配货单
        $("#distributionDemandPlanBtnProduce").click(function(){
            var checkRows = table.checkStatus('distributionDemandPlanTable');
            checkRows.data = checkedData;
            if (checkRows.data.length > 0) {
                createOrderBlank(checkRows.data , '0');

                /*let newCheckRowsData = []
                checkRows.data.forEach((item,index)=>{
                   if (item.status == 'replay'){
                       newCheckRowsData.push(item)
                   }
                })
                if(newCheckRowsData.length>0){
                    newCheckRowsData.forEach((item, index) => {
                        newCheckRowsData[index].quantityConfirm = newCheckRowsData[index].planReplenishment;
                    })
                    createOrderBlank(newCheckRowsData, '0');
                }else {
                    layer.msg('选择的配货单已全部生成', {icon: 5});
                }*/
            } else {
                layer.msg('请选择要生成配货单的数据', {icon: 2});
            }
        });

        // 生成配货单
        function createOrderBlank(data,orderType) {
            admin.open({
                type: 1,
                area: '1500px',
                offset: '65px',
                title: '生成配货单',
                content: $('#distributionOrderTableTemp').html(),
                success: function () {
                    let addPlanIdData = data;
                    addPlanIdData.forEach(item=>{
                        item.planId = item.id;
                        item.LAY_CHECKED = true;
                    });
                    distributionOrder(addPlanIdData, orderType);
                }
            });
        }

        // 配货需求单表格
        function distributionOrder(tableData, orderType){
            if(orderType == '1') {
                $("#batchProduce").hide();
            } else {
                $("#batchProduce").show();
            }
            distributionOrderTable = table.render({
                elem: '#distributionOrderTable',
                data: tableData,
                page: false,
                width: 1460,
                cellMinWidth: 110,
                cols: [[
                    {type: orderType === '0' ? 'checkbox' : 'numbers'}
                    ,{field: 'disbCode',title: '需求编号'}
                    ,{field: 'workshopName', sort: true, title: '所属车间'}
                    ,{field: 'cabCode', title: '柜子编号'}
                    ,{field: 'workshopId', title: '物料编号'}
                    ,{field: 'workshopId', title: '物料名称'}
                    ,{field: 'specCode', title: '规格'}
                    ,{field: 'unitId', title: '单位'}
                    ,{field: 'curentStock', sort: true, title: '当前库存'}
                    ,{field: 'alarmStock', sort: true, title: '告警数'}
                    ,{field: 'planReplenishment', sort: true, title: '计划补货'}
                    ,{field: 'quantityConfirm',fixed: 'right', title: '确认配货数',editor: 'input', templet: function (d) {
                            return '<input signId="'+ d.id +'" class="layui-input productAmount" style="height: 28px;" type="text" ' +
                                'value="'+ d.quantityConfirm +'" />'
                        }
                    }
                    ,{align: 'center', toolbar: orderType === '0' ? '#distributionOrderTableBar2' : '#distributionOrderTableBar',
                        fixed: 'right', title: '操作', width: 180}
                ]],
            });
            // 工具条点击事件
            table.on('tool(distributionOrderTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'dtl') { //详情
                    showDetailModel(data);
                } else if (obj.event === 'affirm') {
                    let checkData = [];
                    checkData.push(data);
                    distributionDemandAdd(checkData);
                }
            });

            // 监听确认配货数
            $("body").delegate(".productAmount","change", function() {
                let id = $(this).attr('signId');
                let value = $(this).val();
                let reg = /^[1-9]+[0-9]*$/;
                tableData.forEach((item, index) => {
                    if ((item.id === id)) {
                        let planReplenishment = Number(item.planReplenishment);
                        let quantityConfirm = Number(value);
                        if(!reg.test(value)) {
                            layer.msg('请输入正确的数字', { icon: 2 });
                            tableData[index].quantityConfirm = planReplenishment;
                            return false;
                        }
                        if(quantityConfirm > planReplenishment) {
                            layer.msg('确认配货数量不能大于计划数量', { icon: 2 });
                            tableData[index].quantityConfirm = planReplenishment;
                            return false;
                        }
                        tableData[index].quantityConfirm = quantityConfirm;
                    }
                });
                table.reload('distributionOrderTable', {
                    data: tableData,
                });
            });

            // 确认批量生成配货单
            $("#batchProduce").click(function(){
                let checkRows = table.checkStatus('distributionOrderTable').data;
                checkRows.forEach((item, index) => {
                    checkRows[index].addNum = tableData[index].quantityConfirm;
                });
                if (checkRows.length == 0) {
                    layer.msg('请选择要确认生成配货单的数据', {icon: 2});
                    return false;
                }
                distributionDemandAdd(checkRows);
            });
        }

        // 生成配货单
        function distributionDemandAdd(data) {
            admin.req('enterprisecab/order/admin/distributionDemand/addList', JSON.stringify(data), function (res) {
                layer.closeAll('loading');
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('distributionDemandPlanTable');
                    layer.closeAll();
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            },'POST', true, 'application/json; charset=utf-8');
        }

        // 显示详情弹窗
        function showDetailModel(data) {
            admin.open({
                type: 1,
                area: '1400px',
                offset: '65px',
                title: '配货需求详情',
                content: $('#distributionDemandPlanDetail').html(),
                success: function () {
                    var alarmList = [];
                    admin.reqSync('enterprisecab/order/admin/inventoryAlarm/getInventoryAlarmById', {id: data.alarmId}, function (res) {
                        if (res.code == 200) {
                            if(Object.keys(res.data).length > 0){
                                alarmList.push(res.data)
                            }
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');
                    var insTb3 = table.render({
                        elem: '#orderDetailTable',
                        data: alarmList,
                        cellMinWidth: 100,
                        cols: [[
                            {field: 'id', title: 'ID', width: 60}
                            , {field: 'alarmCode', title: '告警编号'}
                            , {field: 'cabCode', title: '柜子编号'}
                            , {field: 'workshopName', title: '车间'}
                            , {field: 'productName', title: '物料系列名称'}
                            ,  {field: 'skuCode', title: '物料编号'}
                            , {field: 'brandName', title: '品牌'}
                            , {field: 'unitId', title: '单位'}
                            , {field: 'curentStock', title: '当前库存'}
                            , {field: 'alarmStock', title: '告警库存'}
                            , {field: 'proposalStock', title: '建议补货'}
                            , {field: 'planReplenishment', title: '计划补货'}
                            , {field: 'statusDesc', title: '状态'}
                            , {field: 'createTime', title: '记录时间'}
                        ]]
                    });
                    var insTb4 = table.render({
                        elem: '#childOrdersTable',
                        url: config.base + 'enterprisecab/order/admin/inventoryAlarmDetail/alarmDetailPageList?alarmId=' + data.alarmId,
                        page: true,
                        cellMinWidth: 100,
                        cols: [[
                            {align: 'center', title: '序号', width: 60, type: 'numbers'}
                            , {field: 'spaceId', title: '所属货道'}
                            , {field: 'spaceCapacity', title: '货道容量'}
                            , {field: 'productUrl', title: '物料图片', templet: function (d) {
                                    return '<img class="alarmImg" src="'+d.productUrl+'" />'
                                }
                            }
                            , {field: 'productName', title: '物料系列名称'}
                            ,  {field: 'skuCode', title: '物料编号'}
                            , {field: 'brandId', title: '品牌'}
                            , {field: 'curentStock', title: '当前库存数'}
                            , {field: 'detailUnit', title: '单位'}
                            , {field: 'quantityMax', title: '最大补货数'}
                            , {field: 'planReplenishment', title: '建议补货'}
                            , {field: 'createTime', title: '时间'}
                        ]]
                    });
                }
            });
        }


    });
</script>